/**
 * 
 */
package org.swing.utility.common.chars;

import io.netty.buffer.ByteBuf;

import java.io.IOException;
import java.nio.charset.UnmappableCharacterException;

/**
 * @author lqnhu
 *
 */
public class AsciiBuf extends ReadOnlyAsciiBuf implements CharBuf {
	public AsciiBuf(ByteBuf data) {
		super(data);
	}

	public AsciiBuf(CharBuf charBuf) {
		this(charBuf.toByteBuf());
	}

	
	public Appendable append(CharSequence csq) throws IOException {
		return append(csq, 0, csq.length());
	}

	
	public Appendable append(CharSequence csq, int start, int end)
			throws IOException {
		if (csq.length() < end) {
			throw new IndexOutOfBoundsException();
		}
		if (csq instanceof ReadOnlyAsciiBuf) {
			content().writeBytes(((ReadOnlyAsciiBuf) csq).content());
		} else {
			for (int i = start; i < end; i++) {
				char c = csq.charAt(i);
				if (c >= '\u0080') {
					throw new UnmappableCharacterException(2);
				}
				content().writeByte((byte) c);
			}
		}
		return this;
	}

	
	public Appendable append(char c) throws IOException {
		if (c >= '\u0080') {
			throw new UnmappableCharacterException(2);
		}
		content().writeByte((byte) c);
		return this;
	}
}
